#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/epoll.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include "base.h"
#include <string.h>

#define MAX_EVENT 10

int setNonblocking(int fd) {
	fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
	return 1;
}

int handleClient(int fd) {

	char buffer[5];
	int len;

	bzero(buffer, 5);

	while ((len = recv(fd, buffer, sizeof(buffer), 0)) > 0) {
		printf("read:::%s\n", buffer);
		bzero(buffer, 5);

	}

	if (len < 0 ||len==0) {
		printf("errno:---%s\n",strerror(errno));
	}

	return len;
}
int main() {

	struct sockaddr_in serverAddr, clientAddr;
	int listenFD;
	int clientFD;
	int sockNum;
	char line[128];

	int fdpl;
	struct epoll_event ev, events[MAX_EVENT];
	int dReady;

	socklen_t socklen;

	bzero(&serverAddr, sizeof(listenFD));
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(SERVER_PORT);
	serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); /** INADDR_ANY means let the kernel pick up the address for you when a tcp connection comes.*/

	//inet_pton(AF_INET,"127.0.0.1",&serverAdd.sin_addr);   ---  this function applies to both ipv4 and ipv6

	listenFD = socket(AF_INET, SOCK_STREAM, 0);
	setNonblocking(listenFD);

	bind(listenFD, (struct sockaddr *) &serverAddr, sizeof(serverAddr));

	listen(listenFD, MAX_EVENT);

	fdpl = epoll_create(MAX_EVENT);
	ev.data.fd = listenFD;
	ev.events = EPOLLET | EPOLLIN;
	epoll_ctl(fdpl, EPOLL_CTL_ADD, listenFD, &ev);
	dReady = 1;

	while (1) {
		dReady = epoll_wait(fdpl, events, MAX_EVENT, -1);

		for (int i = 0; i < dReady; i++) {
			/*new connections*/
			if (events[i].data.fd == listenFD) {
				clientFD = accept(listenFD, &clientAddr, &socklen);
				setNonblocking(clientFD);
				ev.data.fd = clientFD;
				ev.events = EPOLLET | EPOLLIN;
				epoll_ctl(fdpl, EPOLL_CTL_ADD, clientFD, &ev);
				printf("get a new connection::%s\n",
						inet_ntoa(clientAddr.sin_addr));
			} else {
				if (handleClient(events[i].data.fd) < 0) {
					/*ev.data.fd = events[i].data.fd;
					ev.events = EPOLLET | EPOLLIN;
					epoll_ctl(fdpl, EPOLL_CTL_MOD, clientFD, &ev);*/
					continue;
				}
			}
		}
	}

	close(listenFD);
	exit(EXIT_SUCCESS);

}
